package com.thread.threadpractice.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import com.thread.threadpractice.entity.Product;
import com.thread.threadpractice.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@RestController
public class ExcelController {
    @Autowired
    private ProductService productService;

    @RequestMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        Integer excel_num = 10;
        List<Product> productList = productService.selectAll();
        String path = System.getProperty("user.dir");
        List<CompletableFuture<String>> futures = new ArrayList<>();

        File folder = new File(path + "/excels");
        if (!folder.exists()) {
            folder.mkdirs();
        }

        for (int i = 0; i < excel_num; i++) {
            List<Product> productListBatch = new ArrayList<>();
            for (Product product : productList) {
                if (product.getId() % excel_num == i) {
                    productListBatch.add(product);
                }
            }
            String filePath = path + "/excels/product_" + (i+1) + ".xlsx";
            futures.add(productService.exportBatch(productListBatch, filePath));
        }

        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        File zipFile = ZipUtil.zip(folder);
        FileUtil.writeToStream(zipFile, response.getOutputStream());
        zipFile.delete();
    }

    @PostMapping("/importExcel")
    public String importExcel(@RequestParam MultipartFile file) throws IOException {
        String path = System.getProperty("user.dir");
        File unzipDir = new File(path);
        File zipFile = new File(path, file.getOriginalFilename());
        file.transferTo(zipFile);

        File folder = new File(path + "/excels");
        if (!folder.exists()) {
            folder.mkdirs();
        }

        File unzipResult = ZipUtil.unzip(zipFile, folder);
        File[] files = unzipResult.listFiles();
        if (files != null) {
            for (File fileChild : files) {
                productService.insertExcel(fileChild);
            }
        }
        zipFile.delete();
        return "导入任务已执行！";
    }

}
